from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *

import opsR

from rpy import r

from opgam import Ui_Dialog

class Dialog(QDialog, Ui_Dialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.setupUi(self)
        self.layer = iface.mapCanvas().currentLayer()
        if not self.layer:
            return 
        self.layerName.setText(self.layer.name())
        self.attrPopulation.clear()
        self.attrObserved.clear()
        provider = self.layer.dataProvider()
        fields = provider.fields()
        valid=['integer','double', 'Real', 'Integer','Double','real', 'numeric','Numeric','number','Number','float','Float']
        [self.attrPopulation.addItem(x.name()) for x in fields.values() if x.typeName() in valid]
        [self.attrObserved.addItem(x.name()) for x in fields.values() if x.typeName() in valid]

    def accept(self):
        """ now build a data frame and run opgam """
        Obs=opsR.getData(self.layer,self.attrObserved.currentText())
        Pop=opsR.getData(self.layer,self.attrPopulation.currentText())
        rate = (1.0*sum(Obs))/(1.0*sum(Pop))
        Exp = [p*rate for p in Pop]
        (x,y) = opsR.getXY(self.layer)
        r.assign("Exp",Exp)
        r.assign("Obs",Obs)
        r.assign("x",x)
        r.assign("y",y)
        r('data = data.frame(Observed=Obs,Expected=Exp,x=x,y=y)')
        s=opsR.summary("data")
        opsR.show(s)
        return
    
    
